﻿/*
 * @author: wizardc
 */

using UnityEngine;
using UnityEngine.UI;

namespace Dou.UI
{
    /// <summary>
    /// 交互组件
    /// 全透明但是需要交互的 UI 可用该组件，可以避免需要挂载 Image 或者 RawImage 之后再设定透明图片的步骤。
    /// 1. 不挂 Collider2D 时，按 RectTransform 的区域进行交互；
    /// 2. 挂 Collider2D 时，按 Collider2D 的区域进行交互；
    /// </summary>
    [RequireComponent(typeof(CanvasRenderer))]
    public class Interaction : Graphic, ICanvasRaycastFilter
    {
        private Collider2D _collider;

        public Collider2D collider
        {
            get
            {
                if (_collider == null)
                {
                    _collider = GetComponent<Collider2D>();
                }
                return _collider;
            }
        }
        
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();
        }
        
        public bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
        {
            var collider = this.collider;
            if (collider == null)
            {
                return RaycastUI(screenPoint, eventCamera);
            }
            return RaycastCollider(screenPoint, eventCamera, collider);
        }

        private bool RaycastUI(Vector2 screenPoint, Camera eventCamera)
        {
            return RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPoint, eventCamera, out _);
        }

        private bool RaycastCollider(Vector2 screenPoint, Camera eventCamera, Collider2D collider)
        {
            return collider.OverlapPoint(eventCamera.ScreenToWorldPoint(screenPoint));
        }
    }
}
